/**
 * Initiator class that creates instances of the other classes needed for the game.
 * 
 */


package gameInitialization;
import gameLogic.*;
import gameView.ViewHandler;

import adapterLayer.Adapter;

import java.awt.Rectangle;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import javax.swing.JOptionPane;

/**
 * Initiator.java
 * 
 * Fredrik Wallenius and Peter Steiner 
 * DP08 - KTH - 2009
 *
 */
public class Initiator {
	private ElementHandler lnkElementHandler;
	
	public final static int WIDTH = 1024;  
	public final static int HEIGHT = 1280; 
	public final static Rectangle box = new Rectangle(WIDTH, HEIGHT);
	public final static String SAVEFILENAME = "highscores.dat";
	
	private ArrayList<TrackEngine> loadedTracks = new ArrayList<TrackEngine>();
	private highScoreHandler hsHandler;
	TrackEngine currentTrack;
	
	
	/**
	 * Initiates the game and enters the endless game-loop. 
	 */
	public Initiator() {

		int choice = -1;
		
		loadedTracks.add(new Track000());
		loadedTracks.add(new Track001());
		loadedTracks.add(new Track002());
		
		TrackChooser tc = new TrackChooser(); 
		for(TrackEngine track : loadedTracks)
			tc.addTrackToList(track.getTrackName());
		
		Adapter adapter;
		ViewHandler vh;
		
		hsHandler = LoadData(SAVEFILENAME);

		
		do{
			choice = tc.getTrack();
			if(choice == TrackChooser.EXIT)
				System.exit(0);
			else currentTrack = loadedTracks.get(choice);
			
			adapter = new Adapter();
			for(int i = 0; i<5; i++){
				adapter.setTopList(i, hsHandler.getHolderName(currentTrack.getTrackId(), i), hsHandler.getHolderTime(currentTrack.getTrackId(), i));
			}
			vh = new ViewHandler(adapter);
			
			lnkElementHandler = new ElementHandler(adapter);
			currentTrack.setElementHandler(lnkElementHandler);
			currentTrack.initiateTrack();

			
			lnkElementHandler.Start();
			currentTrack.start();
			
			do{
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//While game is not  over! /Peter
			} while(lnkElementHandler.isGameOver());
			
			if(lnkElementHandler.getExitReason() == ElementHandler.OUTOFBALLS){
				JOptionPane.showMessageDialog(null, "Aww, you ran out of balls.\nBetter luck next time!", "Game Over", JOptionPane.INFORMATION_MESSAGE);
			}
			if(lnkElementHandler.getExitReason() == ElementHandler.BRICKSCLEARED){
					String newName = (String)JOptionPane.showInputDialog(
	                null,
	                "You did '" + currentTrack.getTrackName() + "' in "+ lnkElementHandler.getTimeElapsed() + " seconds."
	                + "\nEnter your name for the high score list:",
	                "Wohoo!",
	                JOptionPane.PLAIN_MESSAGE);
					
					if(newName != null && newName.length()>0){
						hsHandler.addNewHighScore(currentTrack.getTrackId(), newName, lnkElementHandler.getTimeElapsed());
						SaveData(hsHandler, SAVEFILENAME);
					}
			}
			
			vh.killIt(); // Dispose windows from last game

			
		} while(true);
	}
	
	/**
	 * Saves the high score data to disk.
	 * 
	 * @param data The highScoreHandler object to save.
	 * @param fileName Save file name.
	 * @return Returns true if save was successful otherwise false.
	 */
	public boolean SaveData(highScoreHandler data, String fileName){
		try{
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fileName));
			out.writeObject(data);
			out.close();
			
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	/**
	 * Loads the high score data from disk.
	 * 
	 * @param fileName Name of the file.
	 * @return Returns a reference to the highScoreHandler object with loaded data.
	 */
	public highScoreHandler LoadData(String fileName){
		highScoreHandler data;
		try{
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
			data = (highScoreHandler) in.readObject();
			in.close();
			
		} catch (Exception e) {
			data = new highScoreHandler();
		}
		return data;
	}
	
}
